package MIU.TwistedLabirynth.pac;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.anddev.andengine.util.Debug;

import android.content.Context;

public class PlayerProfileManager {

	private final String FILENAME = "tl_settings";
	
	private int unlockedLevelId;
	private GameLogicController gameLogicController;

	public PlayerProfileManager(GameLogicController gameLogicController) {
		this.gameLogicController = gameLogicController;
		unlockedLevelId = -1;
		try {
			ReadSettings();
		} catch (IOException e) {
			Debug.e("Some IOException occured.", e);
		}
		
	}

	public boolean isLevelUnlocked(int levelId){
		if((unlockedLevelId + 1 >= levelId)
			|| (unlockedLevelId == -1))
			return true;
		return false;
	}
	
	public void incraseUnlockedLevelNumber(int levelId){
		if(levelId > unlockedLevelId)
			unlockedLevelId++;
		try {
			WriteSettings();
		} catch (IOException e) {
			Debug.e("Some IOException occured.", e);
		}
	}
	
	public void saveBeforeQuit() {
		try {
			WriteSettings();
		} catch (IOException e) {
			Debug.e("Some IOException occured.", e);
		}
	}

	private void WriteSettings() throws IOException {
		FileOutputStream fos = null;
		DataOutputStream dos;
		
		try {
			fos = gameLogicController.openFileOutput(FILENAME, Context.MODE_PRIVATE);

		} catch (FileNotFoundException e) {
			Debug.e("Some IOException occured.", e);
		}
		try {
			dos = new DataOutputStream(fos);
			dos.writeInt(unlockedLevelId);
			dos.writeBoolean(gameLogicController.getSettingsMenu().isMusicEnabled());
			dos.writeInt(gameLogicController.getSettingsMenu().getDifficultyLevel());
			dos.flush();
		} catch (IOException e) {
			Debug.e("Some IOException occured.", e);
		} finally {
			fos.close();
		}

	}
	
	private void ReadSettings() throws IOException {
		FileInputStream fis = null;
		DataInputStream dis;
		dis = new DataInputStream(fis);
		try {
			fis = gameLogicController.openFileInput(FILENAME);
		} catch (FileNotFoundException e) {
			unlockedLevelId = 0;
			WriteSettings();
			return;

		}
		try {
			dis = new DataInputStream(fis);
			unlockedLevelId = dis.readInt();
			gameLogicController.getSettingsMenu().setMusicEnabled(dis.readBoolean());
			gameLogicController.getSettingsMenu().setDifficultyLevel(dis.readInt());
		} catch (IOException e) {
			Debug.e("Some IOException occured.", e);
		} finally {
			fis.close();
		}
	}
}
